package sf.view;

import java.util.regex.PatternSyntaxException;

import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class SearchBox extends JTextField {

	private static final long serialVersionUID = 1L;

	private StandardForm parentForm;

	public SearchBox(StandardForm parentForm) {
		this.parentForm = parentForm;
		setColumns(15);
		getDocument().addDocumentListener(new DocumentListener() {
			public void changedUpdate(DocumentEvent e) {
				filterTable();
			}

			public void insertUpdate(DocumentEvent e) {
				filterTable();
			}

			public void removeUpdate(DocumentEvent e) {
				filterTable();
			}
		});
	}

	private void filterTable() {
		String text = this.getText();

		if (text.length() == 0) {
			parentForm.getBrowser().getTableRowSorter().setRowFilter(null);
		} else {
			try {
				parentForm.getBrowser().getTableRowSorter().setRowFilter(
						RowFilter.regexFilter(text));
			} catch (PatternSyntaxException pse) {
				System.err.println("Bad regex pattern");
			}
		}
	}
}
